package com.compile;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhoulikai on 17/2/17.
 */

public class JavaFileBuilder {
    private IJavaMake javaMake;

    public JavaFileBuilder() {
        javaMake = new JavaMake();
    }

    public boolean generateJavaFile(ParameterClass parameterClass, String outFilePath) {
        if (parameterClass == null) {
            return false;
        }
        ParameterClass.RootBean rootBean = parameterClass.getRoot();
        if (rootBean == null) {
            return false;
        }

        String FileName = rootBean.getName();
        if (FileName == null || "".equals(FileName)) {
            return false;
        }

        //创建类文件
        String javaPath = javaMake.makeJavaFile(FileName, outFilePath);
        if (javaPath == null || "".equals(javaPath)) {
            return false;
        }

        //创建内存类
        List<ParameterClass.RootBean.ClassBean> classBeanList = rootBean.getClassX();

        if (classBeanList != null && !classBeanList.isEmpty()) {
            for (int i = 0; i < classBeanList.size(); i++) {
                ParameterClass.RootBean.ClassBean classBean = classBeanList.get(i);
                if (classBean != null) {
                    IJavaMake.Class cls = new IJavaMake.Class();

                    cls.name = classBean.getName();
                    cls.note = classBean.getValue();
                    cls.modification = IJavaMake.Modification.PUBLIC | IJavaMake.Modification.STATIC;

                    List<IJavaMake.Field> fields = new ArrayList<>();
                    List<ParameterClass.RootBean.ClassBean.KeyBean> keyBeanList = classBean.getKey();
                    if (keyBeanList != null && !keyBeanList.isEmpty()) {
                        for (int j = 0; j < keyBeanList.size(); j++) {
                            ParameterClass.RootBean.ClassBean.KeyBean keyBean = keyBeanList.get(j);
                            if (keyBean != null) {
                                IJavaMake.Field field = new IJavaMake.Field();
                                field.name = keyBean.getName();
                                field.note = keyBean.getValue();
                                field.value = keyBean.getContent();
                                field.modification = IJavaMake.Modification.PUBLIC | IJavaMake.Modification.STATIC | IJavaMake.Modification.FINAL;
                                fields.add(field);
                            }
                        }
                    }
                    javaMake.makeJavaClass(javaPath, cls, fields);
                }

            }
        }

        //自动生成的JAVA文件只能读取,不允许程序员修改
        File file = new File(javaPath);
        if (file.exists()) {
            file.setWritable(false);
            file.setExecutable(false);
            file.setReadable(true);
        }

        return true;
    }
}
